// /*eslint-disable*/
import React from 'react';
import { Form } from 'antd';
import Container from 'components/Container';
// import Button from 'components/BtnComponent';
// 不同节点的不同drawbody
import StartAction from './StartAction';
import EndAction from './EndAction';
import AppAction from './AppAction';
import SwitchAction from './SwitchAction';
import ScriptAction from './ScriptAction';
import styles from './index.module.less';

// 格式化开始节点
const formatStart = ({
  x,
  y,
  values,
  inputParamList,
}) => {
  const input = [];
  if (inputParamList.length) {
    inputParamList.forEach((item) => {
      const key = item.paramKey;
      const inputItem = {
        name: values[`param${key}_name`],
        type: values[`param${key}_type`],
        // default: values[`param${key}_default`],
        id: values[`param${key}_property`],
        required: values[`param${key}_name_required`],
      };
      if (values[`param${key}_default`]) {
        if (values[`param${key}_type`] !== 'string') {
          inputItem.default = JSON.parse(values[`param${key}_default`]);
        } else {
          inputItem.default = values[`param${key}_default`];
        }
      }
      input.push(inputItem);
    });
  }
  return {
    loc: `${x} ${y}`,
    name: values.startName,
    input,
    uuid: 'start',
  };
};

// 格式化app动作节点
const formatApp = ({
  x,
  y,
  values,
  id,
  inputs,
  outputs,
}) => {
  const input = {};
  const output = {};
  // const uuid = `uuid${values[`${id}id`]}`;
  const uuid = id;
  const nick = values[`${id}nick`] || '';
  const description = values[`${id}description`] || '';
  const app = values[`${id}app`];
  const actionName = values[`${id}action`];
  const using = values[`${id}using`];
  const errorStop = values[`${id}errorStop`];
  const join = values[`${id}join`];

  if (inputs && inputs.length) {
    inputs.forEach((item) => {
      input[`${item}`] = values[`${id}input_${item}`];
      // input.push({
      //   [`${item}`]: values[`${id}input_${item}`],
      // });
    });
  }
  if (outputs && outputs.length) {
    outputs.forEach((item) => {
      output[`${item}`] = item;
      // output.push({
      //   [`${item}`]: `$.${item}`,
      // });
    });
  }
  return {
    loc: `${x} ${y}`,
    nick,
    uuid,
    description,
    input,
    output,
    app,
    actionName,
    using,
    errorStop,
    join,
    integration: true,
  };
};

// 格式化script动作节点
const formatScript = ({
  x,
  y,
  values,
  id,
  inputs,
  outputs,
}) => {
  const input = {};
  const output = {};
  const uuid = id;
  const nick = values[`${id}nick`];
  const description = values[`${id}description`];
  const script = values[`${id}scriptMode`];
  const actionName = values[`${id}scriptMode`];
  const errorStop = values[`${id}errorStop`];
  const join = values[`${id}join`];

  if (inputs && inputs.length) {
    inputs.forEach((item) => {
      input[`${item}`] = values[`${id}input_${item}`];
    });
  }
  if (outputs && outputs.length) {
    outputs.forEach((item) => {
      output[`${item}`] = item;
    });
  }
  return {
    loc: `${x} ${y}`,
    nick,
    uuid,
    description,
    input,
    output,
    script,
    actionName,
    errorStop,
    join,
  };
};

const PlayEditDrawer = ({
  nodeInfo,
  visible,
  onClose,
  appList,
  scriptList,
  workFlow,
  setWorkFlow,
}) => {
  const [tasks, setTasks] = React.useState(workFlow.tasks);
  const [startInput, setStartInput] = React.useState([]);
  const { id } = nodeInfo;
  const {
    x,
    y,
    label,
    // type,
    nodeType,
  } = nodeInfo.model;
  const formRef = React.useRef({});

  // form默认值
  React.useEffect(() => {
    const task = tasks.find(item => item.uuid === nodeInfo.id);
    if (!task) return;
    if (workFlow && workFlow.input) {
      const input = workFlow.input.map((item, index) => {
        const {
          name,
          required,
          type,
        } = item;
        formRef.current.setFieldsValue({
          [`param${index}_name`]: name,
          [`param${index}_property`]: item.id,
          [`param${index}_default`]: item.default,
          [`param${index}_name_required`]: required,
          [`param${index}_type`]: type,
        });
        return { paramKey: index };
      });
      setStartInput(input);
    }

    if (nodeType === 'switch') {
      const {
        nick,
        description,
        errorStop,
        join,
        input,
      } = task;
      const express = input.cnd;
      formRef.current.setFieldsValue({
        [`${id}nick`]: nick,
        [`${id}description`]: description,
        [`${id}Express`]: express,
        [`${id}errorStop`]: errorStop,
        [`${id}join`]: join,
      });
    }
  }, [nodeInfo.id]);

  const submit = async ({
    inputParamList,
    inputs,
    outputs,
  }) => {
    const values = await formRef.current.validateFields();
    let arr = [];
    if (label === '流程开始') {
      if (inputParamList.length) {
        setStartInput(inputParamList);
      }
      const index = tasks.findIndex(item => item.uuid === 'start');
      if (index >= 0) {
        arr = [...tasks];
        // eslint-disable-next-line object-curly-newline
        arr.splice(index, 1, formatStart({ x, y, values, inputParamList }));
      } else {
        // eslint-disable-next-line object-curly-newline
        arr = [...tasks, formatStart({ x, y, values, inputParamList })];
      }
      setTasks(arr);
      setWorkFlow({ ...workFlow, tasks: arr, ...formatStart({ values, inputParamList }) });
    }

    if (nodeType === 'app') {
      const index = tasks.findIndex(item => item.uuid === id);
      if (index >= 0) {
        arr = [...tasks];
        arr.splice(index, 1, formatApp({
          x,
          y,
          values,
          id,
          inputs,
          outputs,
        }));
      } else {
        arr = [...tasks, formatApp({
          x,
          y,
          values,
          id,
          inputs,
          outputs,
        })];
      }
      setTasks(arr);
      setWorkFlow({ ...workFlow, tasks: arr });
    }

    if (nodeType === 'script') {
      const index = tasks.findIndex(item => item.uuid === id);
      if (index >= 0) {
        arr = [...tasks];
        arr.splice(index, 1, formatScript({
          x,
          y,
          values,
          id,
          inputs,
          outputs,
        }));
      } else {
        arr = [...tasks, formatScript({
          x,
          y,
          values,
          id,
          inputs,
          outputs,
        })];
      }
      setTasks(arr);
      setWorkFlow({ ...workFlow, tasks: arr });
    }

    if (nodeType === 'switch') {
      const index = tasks.findIndex(item => item.uuid === id);
      if (index >= 0) {
        arr = [...tasks];
        arr.splice(index, 1, {
          nodeType: 'switch',
          loc: `${x} ${y}`,
          nick: values[`${id}nick`],
          uuid: id,
          description: values[`${id}description`],
          input: { cnd: values[`${id}Express`] },
          // express: values[`${id}Express`],
          // output,
          isSwitch: true,
          action: 'branch',
          actionName: 'branch',
          // errorStop,
          // join,
        });
      } else {
        arr = [...tasks, {
          nodeType: 'switch',
          loc: `${x} ${y}`,
          nick: values[`${id}nick`],
          uuid: id,
          description: values[`${id}description`],
          input: { cnd: values[`${id}Express`] },
          // express: values[`${id}Express`],
          isSwitch: true,
          action: 'branch',
          actionName: 'branch',
        }];
      }
      setTasks(arr);
      setWorkFlow({ ...workFlow, tasks: arr });
    }

    onClose();
  };

  // const renderFooter = () => (
  //   <Container flex justify="flex-end" style={{ padding: '0 12px 12px 0' }}>
  //     <Button type="gray" style={{ marginRight: '12px' }}>取消</Button>
  //     <Button onClick={submit}>确定</Button>
  //   </Container>
  // );

  return (
    <Container className={styles.form} style={{ paddingTop: '16px', paddingBottom: '12px' }}>
      <Form
        ref={formRef}
        initialValues={{ startName: '流程开始', endName: '流程结束' }}
      >
        {label === '流程开始' && visible && (
          <StartAction
            formRef={formRef}
            defaultInput={startInput}
            submit={submit}
            onClose={onClose}
          />
        )}
        {nodeType === 'switch' && visible && (
          <SwitchAction
            id={id}
            tasks={tasks}
            formRef={formRef}
            submit={submit}
            onClose={onClose}
          />
        )}
        {nodeType === 'script' && visible && (
          <ScriptAction
            id={id}
            tasks={tasks}
            type={nodeType}
            scriptList={scriptList}
            formRef={formRef}
            submit={submit}
            onClose={onClose}
          />
        )}
        {nodeType === 'app' && visible && (
          <AppAction
            id={id}
            tasks={tasks}
            type={nodeType}
            appList={appList}
            formRef={formRef}
            submit={submit}
            onClose={onClose}
          />
        )}
        {label === '流程结束' && visible && <EndAction formRef={formRef} />}
      </Form>
      {/* {label !== '流程开始' && renderFooter()} */}
    </Container>
  );
};

export default PlayEditDrawer;
